package com.minelx.sqlstructures.statements.clause;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class SelectClauseBuilder {
	private final List<Field> orderedFields;

	private final String tableName;

	public SelectClauseBuilder(String tableName) {
		this.tableName = tableName;
		orderedFields = new ArrayList<>();
	}

	public void add(Field field) {
		if (orderedFields.contains(field)) {
			return;
		}
		orderedFields.add(field);
	}

	public void addAll(List<Field> added) {
		added.forEach(this::add);
	}

	public void remove(Field field) {
		orderedFields.remove(field);
	}

	public void removeAll() {
		orderedFields.clear();
	}

	public Set<Field> getFields() {
		return new HashSet<>(orderedFields);
	}

	public String getTableName() {
		return tableName;
	}

	public SelectClause build() {
		return SelectClause.of(tableName, orderedFields);
	}

	public SelectClauseBuilder copy() {
		SelectClauseBuilder result = new SelectClauseBuilder(tableName);
		orderedFields.forEach(result::add);
		return result;
	}

	public static SelectClause create(String table, List<Field> fields) {
		SelectClauseBuilder selectClauseBuilder = new SelectClauseBuilder(table);
		selectClauseBuilder.addAll(fields);
		return selectClauseBuilder.build();
	}
}
